import colorsys
import random

import cv2
import numpy as np
import os
import zipfile

from PIL import Image

from rasterio.io import MemoryFile

def read_land_cover_3():
    keys_and_color = {}

    all_width = 21600; all_height = 10800
    all_image = np.zeros((all_height, all_width, 4), dtype=np.uint8)

    lon_size = 360; lat_size = 180

    local_pixel_width = 1; local_pixel_height = 1
    local_image = np.zeros((local_pixel_height, local_pixel_width, 4), dtype=np.uint8)

    parent_directory = 'E:\\Other map data\\ESA 2021 10m'
    file_names = os.listdir(parent_directory)
    for file_name in file_names:
        url = os.path.join(parent_directory, file_name)

        zip_file_info = zipfile.ZipFile(url, 'r')
        file_list = zip_file_info.namelist()

        for single_file_name in file_list:
            if single_file_name.endswith('.tif'):
                print(single_file_name)
                single_file = zip_file_info.open(single_file_name)
                print('Start to read')
                content = single_file.read()
                print('Finish reading')
                with MemoryFile(content) as memfile:
                    # 打开内存文件中的 TIFF 数据集
                    with memfile.open() as dataset:
                        # 示例：读取影像数据（numpy 数组）
                        bounds = dataset.bounds

                        lon_gap = bounds.right - bounds.left
                        lat_gap = bounds.bottom - bounds.top

                        pixel_width = round(all_width * lon_gap / lon_size)
                        pixel_height = round(all_height * abs(lat_gap) / lat_size)

                        start_x = round((bounds.left - (-180)) / lon_size * all_width)
                        start_y = round((1 - (bounds.top - (-90)) / lat_size) * all_height)

                        single_pixel_width = dataset.width; single_pixel_height = dataset.height

                        if local_pixel_width != single_pixel_width or local_pixel_height != single_pixel_height:
                            local_image = np.zeros((single_pixel_height, single_pixel_width, 4), dtype=np.uint8)
                            local_pixel_width = single_pixel_width; local_pixel_height = single_pixel_height

                        image_nparray_0 = dataset.read(1)

                        image_array_unique = np.unique(image_nparray_0)
                        print('Finish unifying')

                        for pixel in image_array_unique:
                            if pixel not in keys_and_color:
                                h = random.random(); s = 0.8; v = 0.5
                                color0 = colorsys.hsv_to_rgb(h, s, v)
                                color_r = int(color0[0] * 255); color_g = int(color0[1] * 255); color_b = int(color0[2] * 255)

                                keys_and_color[pixel] = np.array([color_r, color_g, color_b], dtype=np.uint8)

                            single_color = keys_and_color[pixel]
                            local_image[:, :, 0][image_nparray_0 == pixel] = single_color[0]
                            local_image[:, :, 1][image_nparray_0 == pixel] = single_color[1]
                            local_image[:, :, 2][image_nparray_0 == pixel] = single_color[2]
                            local_image[:, :, 3][image_nparray_0 == pixel] = 255

                        print('Finished handling')
                        local_image_resized = cv2.resize(local_image, (pixel_width, pixel_height),
                                                 interpolation=cv2.INTER_AREA)

                        print('Finished resizing')
                        image_area_to_fill = all_image[start_y:start_y + pixel_height, start_x:start_x + pixel_width]
                        condition = image_area_to_fill[:, :, 3] < local_image_resized[:, :, 3]

                        image_area_to_fill[condition] = local_image_resized[condition]
                        t = 11

        t = 11
    return 0

if __name__ == '__main__':

    read_land_cover_3()